Page({
  data: {
    longitude: 116.397428, // 默认北京坐标
    latitude: 39.90923,
    markers: [],
    polyline: [],
    currentPolyline: [], // 当前已飞行的轨迹
    currentAltitude: 0,
    currentVelocity: 0,
    horizontalVelocity: 0,
    verticalVelocity: 0,
    batteryPercentage: 0,
    currentYaw: 0,
    currentMode: 'OFFBOARD',
    flightData: [],
    flightDataLoaded: false,
    interval: null,
    currentIndex: 0,
    isPlaying: false,
    defaultIconPath: "/images/uav.png",
    markerIconPath: "/images/uav.png",  // 添加图标路径
    noIconMarkers: true, // 添加标志，表示不使用图标
    showChart: false,
    altitudeStatus: 'normal',
    velocityStatus: 'normal',
    batteryStatus: 'normal',
    altitudeData: [],
    velocityData: [],
    timeData: [],
    chartContext: null,
    warningThresholds: {
      altitude: { warning: 5, danger: 1 },
      velocity: { warning: 0.1, danger: 0.1 },
      battery: { warning: 0.1, danger: 0.1 }
    },
    selectedPoint: null,  // 添加选中的点数据
    showPointInfo: false, // 是否显示点信息
    panelPosition: '70%', // 初始位置，显示部分内容
    startY: 0,
    startPanelY: 0,
    isPanelExpanded: false,
    currentLongitude: 0,
    currentLatitude: 0,
    playSpeed: 1, // 默认播放速度
    mapFollow: true, // 地图是否跟随飞行器位置
  },

  onLoad() {
    this.mapCtx = wx.createMapContext('map');
    // 先设置默认坐标确保地图可以显示
    console.log("地图页面加载");
    wx.getSystemInfo({
      success: (res) => {
        console.log("系统信息:", res);
      }
    });
    this.loadFlightData();
    this.initChart();
  },

  initChart() {
    const ctx = wx.createCanvasContext('altitudeChart');
    const ctx2 = wx.createCanvasContext('velocityChart');
    this.setData({ chartContext: { altitude: ctx, velocity: ctx2 } });
  },

  drawCharts() {
    const { altitudeData, velocityData, timeData, chartContext, currentIndex } = this.data;
    if (!chartContext) return;

    // 只绘制到当前播放进度的数据
    const currentAltitudeData = altitudeData.slice(0, currentIndex);
    const currentVelocityData = velocityData.slice(0, currentIndex);
    const currentTimeData = timeData.slice(0, currentIndex);

    // 绘制高度图表
    this.drawLineChart(chartContext.altitude, 'altitudeChart', currentAltitudeData, currentTimeData, '高度变化', '#0066FF');
    // 绘制速度图表
    this.drawLineChart(chartContext.velocity, 'velocityChart', currentVelocityData, currentTimeData, '速度变化', '#FF6600');
  },

  drawLineChart(ctx, canvasId, data, timeData, title, color) {
    const width = 300;
    const height = 200;
    const padding = 30;

    // 清空画布
    ctx.clearRect(0, 0, width, height);

    if (data.length === 0) return;

    // 计算数据范围
    const maxValue = Math.max(...data);
    const minValue = Math.min(...data);
    const valueRange = maxValue - minValue || 1; // 避免除以0

    // 绘制坐标轴
    ctx.setStrokeStyle('#ccc');
    ctx.setLineWidth(1);
    ctx.moveTo(padding, padding);
    ctx.lineTo(padding, height - padding);
    ctx.lineTo(width - padding, height - padding);
    ctx.stroke();

    // 绘制折线图
    ctx.setStrokeStyle(color);
    ctx.setLineWidth(2);
    
    // 绘制折线
    data.forEach((value, index) => {
      const x = padding + (index * (width - 2 * padding)) / (data.length - 1);
      const y = height - padding - ((value - minValue) * (height - 2 * padding)) / valueRange;
      
      if (index === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
    });
    ctx.stroke();

    // 绘制标题和当前值
    ctx.setFontSize(12);
    ctx.setFillStyle('#333');
    
    // 绘制Y轴刻度
    const yStep = valueRange / 4;
    for (let i = 0; i <= 4; i++) {
      const y = height - padding - (i * (height - 2 * padding)) / 4;
      const value = minValue + i * yStep;
      ctx.fillText(value.toFixed(1), 5, y + 4);
    }

    // 绘制X轴刻度
    const xStep = Math.floor(data.length / 4);
    for (let i = 0; i <= 4; i++) {
      const x = padding + (i * (width - 2 * padding)) / 4;
      const time = i * xStep;
      ctx.fillText(time.toString(), x - 10, height - padding + 15);
    }

    // 绘制标题
    ctx.fillText(title, padding, padding - 10);

    // 绘制当前值
    if (data.length > 0) {
      const currentValue = data[data.length - 1];
      ctx.fillText(`当前: ${currentValue.toFixed(2)}`, width - padding - 80, padding - 10);
    }

    ctx.draw();
  },

  // ✅ 从后端获取飞行数据
  loadFlightData() {
    const self = this;
    wx.request({
      url: 'http://120.46.23.123:1818/flight/file',
      method: 'GET',
      success(res) {
        console.log("获取到的飞行数据:", res.data);
        if (res.data && res.data.data) {
          const flightData = res.data.data;
          // 准备图表数据
          const altitudeData = flightData.map(point => parseFloat(point.altitude));
          const velocityData = flightData.map(point => {
            const vx = parseFloat(point.velocity_x);
            const vy = parseFloat(point.velocity_y);
            const vz = parseFloat(point.velocity_z);
            return Math.sqrt(vx * vx + vy * vy + vz * vz);
          });
          const timeData = flightData.map((_, index) => index);

          self.setData({
            flightData,
            longitude: flightData[0].longitude,
            latitude: flightData[0].latitude,
            currentLongitude: flightData[0].longitude,
            currentLatitude: flightData[0].latitude,
            currentIndex: 0,
            flightDataLoaded: true,
            altitudeData,
            velocityData,
            timeData
          });
          self.drawPolyline();
          // 初始化时绘制一次图表
          self.drawCharts();
        } else {
          console.error('飞行数据格式错误');
          wx.showToast({
            title: '数据加载失败',
            icon: 'none'
          });
        }
      },
      fail(err) {
        console.error('请求飞行数据失败:', err);
        wx.showToast({
          title: '网络请求失败',
          icon: 'none'
        });
      }
    });
  },

  // ✅ 绘制轨迹线
  drawPolyline() {
    if (!this.data.flightData || this.data.flightData.length === 0) {
      console.log('没有飞行数据可绘制');
      return;
    }

    // 只在播放状态下显示轨迹线
    if (!this.data.isPlaying) {
      // 不显示轨迹线，只显示起点标记
      const startPoint = this.data.flightData[0];
      const markers = [{
        id: 1,
        latitude: startPoint.latitude,
        longitude: startPoint.longitude,
        width: 30,
        height: 30,
        iconPath: this.data.markerIconPath,
        callout: {
          content: '起点',
          display: 'ALWAYS',
          color: '#ffffff',
          bgColor: '#1296db',
          borderRadius: 6,
          padding: 4,
          fontSize: 12,
          textAlign: 'center',
          borderWidth: 1,
          borderColor: '#0d7ab8',
          anchorX: 0,
          anchorY: 0
        }
      }];
      
      this.setData({
        markers: markers,
        polyline: [] // 不显示轨迹线
      });
      return;
    }

    // 播放状态下显示轨迹线
    // 每隔20个点显示一个标记
    const MARKER_INTERVAL = 20;
    const markers = [];
    
    // 创建航迹点标记
    this.data.flightData.forEach((point, index) => {
      // 每隔MARKER_INTERVAL个点显示一个标记，或者是在关键点（如起点、终点）
      if (index % MARKER_INTERVAL === 0 || index === 0 || index === this.data.flightData.length - 1) {
        markers.push({
          id: markers.length + 1,
          latitude: point.latitude,
          longitude: point.longitude,
          width: 8,
          height: 8,
          callout: {
            content: `${index + 1}`,
            display: 'ALWAYS',
            color: '#ffffff',
            bgColor: '#1296db',
            borderRadius: 6,
            padding: 4,
            fontSize: 12,
            textAlign: 'center',
            borderWidth: 1,
            borderColor: '#0d7ab8',
            anchorX: 0,
            anchorY: 0
          }
        });
      }
    });

    // 添加当前飞行器位置标记
    const currentIndex = Math.min(this.data.currentIndex, this.data.flightData.length - 1);
    markers.push({
      id: markers.length + 1,
      latitude: this.data.flightData[currentIndex].latitude,
      longitude: this.data.flightData[currentIndex].longitude,
      width: 30,
      height: 30,
      iconPath: this.data.markerIconPath,
      callout: {
        content: '当前位置',
        display: 'ALWAYS',
        color: '#ffffff',
        bgColor: '#1296db',
        borderRadius: 8,
        padding: 8,
        fontSize: 14,
        textAlign: 'center',
        borderWidth: 1,
        borderColor: '#0d7ab8',
        anchorX: 0,
        anchorY: 0
      }
    });

    // 设置标记点和轨迹线
    this.setData({
      markers: markers
      // 不更新polyline，保持现有的轨迹线
    });
  },

  // ✅ 开始回放
  startPlayback() {
    // 如果已经在播放，先停止
    if (this.data.interval) {
      clearInterval(this.data.interval);
    }
    
    // 设置播放状态
    this.setData({ isPlaying: true });
    
    // 开始播放
    const interval = setInterval(() => {
      this.updatePosition();
    }, 1000); // 每秒更新一次
    
    this.setData({ interval });
  },

  // ✅ 更新当前位置与飞行状态
  updatePosition() {
    const { flightData, currentIndex, noIconMarkers, warningThresholds } = this.data;
    if (!flightData || currentIndex >= flightData.length) {
      this.pause(); // 播放结束时自动暂停
      return;
    }

    const currentPoint = flightData[currentIndex];
    
    // 计算速度
    const velocity_x = parseFloat(currentPoint.velocity_x);
    const velocity_y = parseFloat(currentPoint.velocity_y);
    const velocity_z = parseFloat(currentPoint.velocity_z);
    
    // 计算总速度
    const totalVelocity = Math.sqrt(
      Math.pow(velocity_x, 2) + 
      Math.pow(velocity_y, 2) + 
      Math.pow(velocity_z, 2)
    );
    
    // 计算水平速度
    const horizontalVelocity = Math.sqrt(
      Math.pow(velocity_x, 2) + 
      Math.pow(velocity_y, 2)
    );
    
    // 计算航向（转换为角度并标准化到0-360度）
    const yawInDegrees = (parseFloat(currentPoint.yaw) * 180 / Math.PI) % 360;
    const normalizedYaw = yawInDegrees < 0 ? yawInDegrees + 360 : yawInDegrees;
    
    // 检查异常状态
    const altitudeStatus = this.checkStatus(parseFloat(currentPoint.relative_altitude), warningThresholds.altitude);
    const velocityStatus = this.checkStatus(Math.abs(totalVelocity), warningThresholds.velocity);
    const batteryStatus = this.checkStatus(parseFloat(currentPoint.battery_percentage), warningThresholds.battery);
    
    // 如果发现异常，显示警告
    if (altitudeStatus === 'danger' || velocityStatus === 'danger' || batteryStatus === 'danger') {
      this.showWarning(altitudeStatus, velocityStatus, batteryStatus);
    }
    
    let markers = [];
    if (noIconMarkers) {
      markers = [{
        id: 1,
        latitude: currentPoint.latitude,
        longitude: currentPoint.longitude,
        callout: {
          content: '飞行器',
          display: 'ALWAYS',
          color: '#ffffff',
          bgColor: '#FF0000',
          borderRadius: 5,
          padding: 8,
          fontSize: 12
        }
      }];
    } else {
      markers = [{
        id: 1,
        latitude: currentPoint.latitude,
        longitude: currentPoint.longitude,
        width: 30,
        height: 30,
        iconPath: this.data.markerIconPath,
        callout: {
          content: '当前位置',
          display: 'ALWAYS',
          color: '#ffffff',
          bgColor: '#1296db',
          borderRadius: 8,
          padding: 8,
          fontSize: 14,
          textAlign: 'center',
          borderWidth: 1,
          borderColor: '#0d7ab8',
          anchorX: 0,
          anchorY: 0
        }
      }];
    }
    
    // 更新图表数据
    const newAltitudeData = [...this.data.altitudeData];
    const newVelocityData = [...this.data.velocityData];
    const newTimeData = [...this.data.timeData];

    // 保持最近30个数据点
    const maxDataPoints = 30;
    if (newAltitudeData.length >= maxDataPoints) {
      newAltitudeData.shift();
      newVelocityData.shift();
      newTimeData.shift();
    }

    newAltitudeData.push(parseFloat(currentPoint.altitude));
    newVelocityData.push(totalVelocity);
    newTimeData.push(currentIndex);
    
    this.setData({
      longitude: currentPoint.longitude,
      latitude: currentPoint.latitude,
      markers: markers,
      currentAltitude: currentPoint.altitude,
      currentVelocity: totalVelocity.toFixed(2),
      horizontalVelocity: horizontalVelocity.toFixed(2),
      verticalVelocity: velocity_z.toFixed(2),
      batteryPercentage: currentPoint.battery_percentage * 100,
      currentYaw: normalizedYaw.toFixed(1),
      currentMode: currentPoint.mode,
      currentIndex: currentIndex + 1,
      altitudeStatus,
      velocityStatus,
      batteryStatus,
      altitudeData: newAltitudeData,
      velocityData: newVelocityData,
      timeData: newTimeData
    });

    // 如果图表显示，则更新图表
    if (this.data.showChart) {
      this.drawCharts();
    }
  },

  checkStatus(value, thresholds) {
    if (value <= thresholds.danger) {
      return 'danger';
    } else if (value <= thresholds.warning) {
      return 'warning';
    } else {
      return 'normal';
    }
  },

  showWarning(altitudeStatus, velocityStatus, batteryStatus) {
    let warningMessage = '';
    if (altitudeStatus === 'danger') warningMessage += '高度异常！';
    if (velocityStatus === 'danger') warningMessage += '速度异常！';
    if (batteryStatus === 'danger') warningMessage += '电量过低！';

    wx.showToast({
      title: warningMessage,
      icon: 'none',
      duration: 2000
    });
  },

  toggleChart() {
    this.setData({
      showChart: !this.data.showChart
    });
  },

  onRegionChange(e) {
    // console.log('地图区域变化:', e);
  },

  onMapTap(e) {
    const { latitude, longitude } = e.detail;
    console.log('地图点击坐标:', latitude, longitude);
    
    // 找到最近的点
    const nearestPoint = this.findNearestPoint(latitude, longitude);
    if (nearestPoint) {
      // 预处理数据
      const processedPoint = {
        ...nearestPoint,
        roll: parseFloat(nearestPoint.roll).toFixed(2),
        pitch: parseFloat(nearestPoint.pitch).toFixed(2),
        yaw: (parseFloat(nearestPoint.yaw) * 180 / Math.PI).toFixed(1),
        velocity_x: parseFloat(nearestPoint.velocity_x).toFixed(2),
        velocity_y: parseFloat(nearestPoint.velocity_y).toFixed(2),
        velocity_z: parseFloat(nearestPoint.velocity_z).toFixed(2),
        battery_percentage: (parseFloat(nearestPoint.battery_percentage) * 100).toFixed(1)
      };

      this.setData({
        selectedPoint: processedPoint,
        showPointInfo: true
      });
      
      // 显示提示
      wx.showToast({
        title: '已选择最近点',
        icon: 'success',
        duration: 1500
      });
    }
  },

  findNearestPoint(latitude, longitude) {
    if (!this.data.flightData || this.data.flightData.length === 0) {
      return null;
    }

    let nearestPoint = null;
    let minDistance = Infinity;

    // 将经纬度转换为数值
    const targetLat = parseFloat(latitude);
    const targetLng = parseFloat(longitude);

    // 计算点击点与轨迹上每个点的距离
    this.data.flightData.forEach(point => {
      const pointLat = parseFloat(point.latitude);
      const pointLng = parseFloat(point.longitude);
      
      // 使用更精确的距离计算方法
      const distance = this.calculateDistance(targetLat, targetLng, pointLat, pointLng);

      if (distance < minDistance) {
        minDistance = distance;
        nearestPoint = point;
      }
    });

    // 设置一个合理的阈值（例如100米）
    const threshold = 100; // 100米
    console.log('最近点距离:', minDistance, '米');
    
    if (minDistance <= threshold) {
      console.log('找到最近点:', nearestPoint);
      return nearestPoint;
    }
    
    console.log('未找到符合条件的点');
    return null;
  },

  // 计算两点之间的距离（使用Haversine公式）
  calculateDistance(lat1, lon1, lat2, lon2) {
    const R = 6371e3; // 地球半径（米）
    const φ1 = lat1 * Math.PI / 180;
    const φ2 = lat2 * Math.PI / 180;
    const Δφ = (lat2 - lat1) * Math.PI / 180;
    const Δλ = (lon2 - lon1) * Math.PI / 180;

    const a = Math.sin(Δφ/2) * Math.sin(Δφ/2) +
              Math.cos(φ1) * Math.cos(φ2) *
              Math.sin(Δλ/2) * Math.sin(Δλ/2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));

    return R * c; // 返回距离（米）
  },

  closePointInfo() {
    this.setData({
      showPointInfo: false,
      selectedPoint: null
    });
  },

  // 修改播放方法
  play() {
    if (this.data.isPlaying) {
      return;
    }
    
    if (!this.data.flightData || this.data.flightData.length === 0) {
      wx.showToast({
        title: '请先加载数据',
        icon: 'none'
      });
      return;
    }

    const startIndex = this.data.currentIndex >= this.data.flightData.length ? 0 : this.data.currentIndex;
    
    // 确保currentPolyline和polyline已经初始化
    if (!this.data.currentPolyline) {
      this.setData({
        currentPolyline: []
      });
    }
    
    // 确保polyline数组已初始化
    if (!this.data.polyline) {
      this.setData({
        polyline: []
      });
    }
    
    this.setData({ 
      isPlaying: true,
      currentIndex: startIndex
    });

    // 重新绘制轨迹线，开始显示轨迹
    this.drawPolyline();

    // 如果图表显示，确保在开始播放时绘制一次
    if (this.data.showChart) {
      this.drawCharts();
    }

    const updateInterval = 1000 / this.data.playSpeed;

    this.playInterval = setInterval(() => {
      if (this.data.currentIndex < this.data.flightData.length) {
        const currentPoint = this.data.flightData[this.data.currentIndex];
        
        // 更新标记点，只显示当前位置
        const markers = [{
          id: 1,
          latitude: currentPoint.latitude,
          longitude: currentPoint.longitude,
          width: 30,
          height: 30,
          iconPath: this.data.markerIconPath,
          callout: {
            content: '当前位置',
            display: 'ALWAYS',
            color: '#ffffff',
            bgColor: '#1296db',
            borderRadius: 8,
            padding: 8,
            fontSize: 14,
            textAlign: 'center',
            borderWidth: 1,
            borderColor: '#0d7ab8',
            anchorX: 0,
            anchorY: 0
          }
        }];

        // 确保所有数值都是数字类型
        const yaw = parseFloat(currentPoint.yaw) || 0;
        const velocity_x = parseFloat(currentPoint.velocity_x) || 0;
        const velocity_y = parseFloat(currentPoint.velocity_y) || 0;
        const velocity_z = parseFloat(currentPoint.velocity_z) || 0;
        const altitude = parseFloat(currentPoint.altitude) || 0;
        const battery_percentage = parseFloat(currentPoint.battery_percentage) || 0;
        
        // 计算速度值
        const totalVelocity = Math.sqrt(
          Math.pow(velocity_x, 2) +
          Math.pow(velocity_y, 2) +
          Math.pow(velocity_z, 2)
        ).toFixed(2);
        
        const horizontalVelocity = Math.sqrt(
          Math.pow(velocity_x, 2) +
          Math.pow(velocity_y, 2)
        ).toFixed(2);
        
        const verticalVelocity = Math.abs(velocity_z).toFixed(2);

        // 计算航向角（弧度转角度，并标准化到0-360度）
        const yawInDegrees = (yaw * 180 / Math.PI) % 360;
        const normalizedYaw = yawInDegrees < 0 ? yawInDegrees + 360 : yawInDegrees;

        // 批量更新数据，减少setData调用次数
        const updateData = {
          longitude: currentPoint.longitude,
          latitude: currentPoint.latitude,
          currentLongitude: currentPoint.longitude,
          currentLatitude: currentPoint.latitude,
          currentAltitude: altitude,
          currentVelocity: totalVelocity,
          horizontalVelocity: horizontalVelocity,
          verticalVelocity: verticalVelocity,
          batteryPercentage: (battery_percentage * 100).toFixed(1),
          currentYaw: normalizedYaw.toFixed(1),
          currentMode: currentPoint.mode,
          altitudeStatus: this.getStatus(altitude, 100, 200),
          velocityStatus: this.getStatus(totalVelocity, 10, 20),
          batteryStatus: this.getStatus(battery_percentage * 100, 30, 50),
          currentIndex: this.data.currentIndex + 1,
          markers: markers
        };

        // 更新轨迹
        const newPoint = {
          longitude: currentPoint.longitude,
          latitude: currentPoint.latitude
        };

        // 获取当前速度对应的颜色
        const currentColor = this.getSpeedColor(totalVelocity);
        
        // 更新所有轨迹段
        const allPolylines = this.data.polyline || [];
        const lastPolyline = allPolylines.length > 0 ? allPolylines[allPolylines.length - 1] : null;
        
        if (lastPolyline && lastPolyline.color === currentColor && lastPolyline.points) {
          // 如果最后一个轨迹段颜色相同，继续添加点
          lastPolyline.points.push(newPoint);
        } else {
          // 如果颜色不同，创建新的轨迹段
          // 确保新轨迹段的第一个点是上一个轨迹段的最后一个点
          let lastPoint = newPoint;
          if (lastPolyline && lastPolyline.points && lastPolyline.points.length > 0) {
            lastPoint = lastPolyline.points[lastPolyline.points.length - 1];
          }
          allPolylines.push({
            points: [lastPoint, newPoint],
            color: currentColor,
            width: 4,
            arrowLine: true
          });
        }

        updateData.polyline = allPolylines;
        
        // 更新当前已飞行的轨迹
        const currentPolyline = this.data.currentPolyline || [];
        currentPolyline.push(newPoint);
        updateData.currentPolyline = currentPolyline;
        
        // 一次性更新所有数据
        this.setData(updateData);

        // 如果图表显示，则更新图表
        if (this.data.showChart) {
          this.drawCharts();
        }
      } else {
        this.pause();
      }
    }, updateInterval);
  },

  pause() {
    if (!this.data.isPlaying) return;
    
    clearInterval(this.playInterval);
    this.setData({
      isPlaying: false
    });
    
    // 暂停时保持在当前航迹，但不调用drawPolyline，因为它会清空轨迹线
    // 只更新标记点
    const currentIndex = Math.min(this.data.currentIndex, this.data.flightData.length - 1);
    const currentPoint = this.data.flightData[currentIndex];
    
    const markers = [{
      id: 1,
      latitude: currentPoint.latitude,
      longitude: currentPoint.longitude,
      width: 30,
      height: 30,
      iconPath: this.data.markerIconPath,
      callout: {
        content: '当前位置',
        display: 'ALWAYS',
        color: '#ffffff',
        bgColor: '#1296db',
        borderRadius: 8,
        padding: 8,
        fontSize: 14,
        textAlign: 'center',
        borderWidth: 1,
        borderColor: '#0d7ab8',
        anchorX: 0,
        anchorY: 0
      }
    }];
    
    this.setData({
      markers: markers
    });

    // 确保图表保持在当前状态
    if (this.data.showChart) {
      this.drawCharts();
    }
  },

  stop() {
    console.log('停止播放');
    this.pause();
    this.setData({
      currentIndex: 0,
      currentLongitude: this.data.flightData[0].longitude,
      currentLatitude: this.data.flightData[0].latitude,
      currentPolyline: [],
      polyline: []
    });
    this.drawPolyline();
  },

  replay() {
    console.log('重新播放');
    this.stop();
    this.play();
  },

  // 在页面中添加地图加载错误处理
  onMapError(e) {
    console.error("地图加载错误:", e.detail);
    wx.showToast({
      title: '地图加载失败，请检查网络',
      icon: 'none'
    });
  },

  onTouchStart(e) {
    this.setData({
      startY: e.touches[0].clientY,
      startPanelY: parseInt(this.data.panelPosition)
    });
  },

  onTouchMove(e) {
    const currentY = e.touches[0].clientY;
    const diff = currentY - this.data.startY;
    const newPosition = this.calculatePanelPosition(diff);
    
    this.setData({
      panelPosition: newPosition
    });
  },

  onTouchEnd(e) {
    const currentY = e.changedTouches[0].clientY;
    const diff = currentY - this.data.startY;
    
    // 根据滑动距离和方向决定最终位置
    let finalPosition;
    if (Math.abs(diff) < 50) {
      // 如果滑动距离小，切换展开/收起状态
      finalPosition = this.data.isPanelExpanded ? '70%' : '30%';
      this.setData({
        isPanelExpanded: !this.data.isPanelExpanded
      });
    } else if (diff > 0) {
      // 向下滑动，展开面板
      finalPosition = '30%';
      this.setData({
        isPanelExpanded: true
      });
    } else {
      // 向上滑动，收起面板
      finalPosition = '70%';
      this.setData({
        isPanelExpanded: false
      });
    }
    
    this.setData({
      panelPosition: finalPosition
    });
  },

  calculatePanelPosition(diff) {
    const currentPosition = parseInt(this.data.startPanelY);
    const newPosition = currentPosition + diff;
    
    // 限制滑动范围在30%到70%之间
    if (newPosition < 30) return '30%';
    if (newPosition > 70) return '70%';
    return newPosition + '%';
  },

  getStatus(value, lowerWarning, upperWarning) {
    if (value < lowerWarning) {
      return 'danger';
    } else if (value < upperWarning) {
      return 'warning';
    } else {
      return 'normal';
    }
  },

  onSpeedChange(e) {
    const speed = e.detail.value;
    this.setData({
      playSpeed: speed
    });
    
    // 如果正在播放，需要重新设置定时器
    if (this.data.isPlaying) {
      this.pause();
      this.play();
    }
  },

  // 根据速度获取对应的颜色
  getSpeedColor(speed) {
    const speedRanges = [
      { min: 0, max: 2.3, color: '#FF0000' },    // 红色
      { min: 2.3, max: 2.4, color: '#FF6600' },  // 橙红色
      { min: 2.4, max: 2.45, color: '#FFCC00' }, // 黄色
      { min: 2.45, max: 2.5, color: '#99FF00' }, // 黄绿色
      { min: 2.5, max: Infinity, color: '#00FF00' } // 绿色
    ];

    const currentSpeed = parseFloat(speed);
    for (const range of speedRanges) {
      if (currentSpeed >= range.min && currentSpeed < range.max) {
        return range.color;
      }
    }
    return '#FF0000'; // 默认红色
  },

  toggleMapFollow() {
    this.setData({
      mapFollow: !this.data.mapFollow
    });
  },
});
